package ru.agiledev.akb.ws;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ru.agiledev.akb.server.domain.Aspect;
import ru.agiledev.akb.server.domain.IObject;
import ru.agiledev.akb.server.hibernate.HibernateUtil;
import ru.agiledev.akb.shared.QType;

import javax.jws.WebService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by a.kirillov
 * Date: 1/26/12 Time: 11:04 PM
 */
@WebService(endpointInterface = "ru.agiledev.akb.ws.AKBService")
public class AKBServiceImpl implements AKBService{

    @Override
    public AKBObject getObject(String word, QType type) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(IObject.class);

        List<IObject> list = criteria.add(Restrictions.eq("value", word.trim().toLowerCase())).list();

        if(list.size() >0){

            IObject target = null;

            if(!QType.DIFFERENCES_DESCRIPTION.equals(type)&&!QType.COMMONS_DESCRIPTION.equals(type)){
                for(IObject iObj:list){
                    if(iObj.getAspects().size()>0){
                        if(iObj.getAspects().get(0).getType().equals(type)){
                            target = iObj;
                            break;
                        }
                    }
                }
                if(target == null) return null;

                List<AKBAspect> aspects = new ArrayList<AKBAspect>();

                List<Aspect> oAspects = target.getAspects();
                for(Aspect aspect: oAspects){
                    aspects.add(new AKBAspect(aspect.getValue()));
                }

                session.close();
                return  new AKBObject(target.getValue(), aspects);
            } else {
                HashSet<String> aspects = new HashSet<String>();

                for(IObject iObj:list){
                    if(iObj.getAspects().size()>0){
                        for(Aspect aspect: iObj.getAspects()){
                            aspects.add(aspect.getValue());
                        }

                    }
                }

                List<AKBAspect> akbAspects = new ArrayList<AKBAspect>();
                 for(String asp: aspects){
                     akbAspects.add(new AKBAspect(asp));
                 }

                session.close();

                if(akbAspects.size() > 0){
                    return  new AKBObject(word.trim(), akbAspects);
                } else {
                    return null;
                }
            }
        }
        session.close();
        return null;
    }
}
